package com.examination.client.aop;

import com.examination.client.util.JsonUtils;
import com.google.common.collect.ImmutableMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.MDC;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.security.Principal;
import java.util.Arrays;
import java.util.Enumeration;

/**
 * @author: XiaoDong
 * @date: 2021-10-18 19:04
 * @description:
 */
@Slf4j
@Aspect
@Component
public class LogAspect {
    private static final String LINE_SEPARATOR = System.getProperty("line.separator");
    private static final ThreadLocal<Long> startTime = new ThreadLocal();
    private static final ThreadLocal<StringBuilder> sb = new ThreadLocal();

    @Pointcut("execution(public * com.examination.client.controller..*.*(..))")
    public void log() {
    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        StringBuilder builder = new StringBuilder();
        startTime.set(System.currentTimeMillis());
        sb.set(builder);
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        builder.append("--------------------begin new------------------------").append(LINE_SEPARATOR);
        builder.append("url : " + request.getRequestURL().toString()).append(LINE_SEPARATOR);
        builder.append("request : " + request.getMethod()).append(LINE_SEPARATOR);
        builder.append("class method : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()).append(LINE_SEPARATOR);
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Object[] objects = joinPoint.getArgs();
        Parameter[] parameters = method.getParameters();

        for (int i = 0; i < parameters.length; ++i) {
            Parameter p = parameters[i];
            if (!p.getType().equals(MultipartFile.class) && !p.getType().equals(HttpServletRequest.class) && !p.getType().equals(HttpServletResponse.class) && !p.getType().equals(Principal.class) && !"bytes".equalsIgnoreCase(p.getName()) && objects[i] != null) {
                try {
                    builder.append("args : " + JsonUtils.toJson(ImmutableMap.of(p.getName(), objects[i]))).append(LINE_SEPARATOR);
                } catch (Exception var12) {
                    log.error("json output args {} error {} ", p.getName(), var12);
                }
            }
        }

        this.builderLoggerMDC(request, joinPoint);
    }

    private void builderLoggerMDC(HttpServletRequest request, JoinPoint joinPoint) {
        try {
            String requestId = request.getHeader("X-Request-Id");
            MDC.put("remoteIp", request.getRemoteAddr());
            MDC.put("requestId", requestId);
            MDC.put("code", "-");
            MDC.put("requestParams", JsonUtils.toJson(Arrays.toString(joinPoint.getArgs())));
            MDC.put("uri", request.getRequestURI());
            MDC.put("queryString", request.getQueryString());
            MDC.put("localIP", request.getLocalAddr());
        } catch (Exception var5) {
            log.error("builderLoggerMDC error={}", var5);
        }

    }

    @AfterReturning(
            pointcut = "log()",
            returning = "ret"
    )
    public void doAfterReturning(Object ret) throws Throwable {
        StringBuilder builder = (StringBuilder) sb.get();
        builder.append("response : " + JsonUtils.toJson(ret)).append(LINE_SEPARATOR);
        builder.append("time : " + (System.currentTimeMillis() - (Long) startTime.get()) + "ms").append(LINE_SEPARATOR);
        builder.append("---------------------end-----------------------").append(LINE_SEPARATOR);
        //log.info(builder.toString());
        MDC.put("code", HttpStatus.OK.value() + "");
        MDC.clear();
    }

    @AfterThrowing(
            pointcut = "log()",
            throwing = "exp"
    )
    public void doAfterThrowing(Exception exp) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        StringBuilder builder = new StringBuilder();
        builder.append("--------------------begin------------------------").append(LINE_SEPARATOR);
        builder.append("url : " + request.getRequestURL().toString()).append(LINE_SEPARATOR);
        builder.append("request : " + request.getMethod()).append(LINE_SEPARATOR);
        Enumeration parameterNames = request.getParameterNames();

        while (parameterNames.hasMoreElements()) {
            String paramName = (String) parameterNames.nextElement();
            String[] paramValues = request.getParameterValues(paramName);
            builder.append("args : " + JsonUtils.toJson(ImmutableMap.of(paramName, paramValues))).append(LINE_SEPARATOR);
        }

        builder.append("exception : " + ExceptionUtils.getStackTrace(exp)).append(LINE_SEPARATOR);
        builder.append("time : " + (System.currentTimeMillis() - (Long) startTime.get()) + "ms").append(LINE_SEPARATOR);
        builder.append("---------------------end-----------------------").append(LINE_SEPARATOR);
        //log.error(builder.toString());

    }
}
